package com.cloud.grainmall.web;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.cloud.common.exception.BisCodeEnum;
import com.cloud.common.utils.R;
import com.cloud.common.vo.MemberRespVo;
import com.cloud.common.constant.AuthServerConstant;
import com.cloud.grainmall.feign.MemberFeignService;
import com.cloud.grainmall.feign.ThirdPartFeignService;
import com.cloud.common.vo.UserLoginVo;
import com.cloud.common.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author lisw
 * @create 2021/7/13 13:57
 */
@Controller
public class HtmlController {

    @Resource
    StringRedisTemplate stringredisTemplate;

    @Resource
    ThirdPartFeignService thirdPartFeignService;

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone")String phone){

        //1、接口防刷

        //进行判断是否过了60s，进行重复发送
        String s = stringredisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_REDIS_PREFIX + phone);
        if (StringUtils.isNotEmpty(s)){
            long l = Long.parseLong(s.split("_")[1]);
            if(System.currentTimeMillis() - l < 60000){
                //60s不能再发
                return R.error(BisCodeEnum.VALID_SMS__CODE_EXCEPTION.getCode(),BisCodeEnum.VALID_SMS__CODE_EXCEPTION.getMsg());
            }
        }
        String substring = UuidUtils.generateUuid().substring(0, 5);
        String UUID = substring + "_" + System.currentTimeMillis();

        //2、验证码的校验  将验证码保存至redis中，并设置过期时间，根据是否过期来验证是否合法
        //redis缓存验证码
        stringredisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_REDIS_PREFIX + phone,UUID , 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendSms(phone,substring);
        return R.ok();
    }


    @PostMapping("regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult result,
                         Model model, RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            return "redirect:http://auth.grainmall.com:81/register";
        }

        //上面的所有校验都通过之后，会执行下面的正确注册服务
        //1、校验验证码
        String code = userRegistVo.getCode();
        String s = stringredisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_REDIS_PREFIX + userRegistVo.getPhone());
        if (StringUtils.isNotEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //验证码通过 删除验证码 类似于令牌机制
                stringredisTemplate.delete(AuthServerConstant.SMS_CODE_REDIS_PREFIX + userRegistVo.getPhone());
                //真正注册，调用远程服务注册
                R regist = memberFeignService.regist(userRegistVo);
                if (regist.get("code").equals(0)){

                    return "redirect:http://auth.grainmall.com:81/login";
                }else {
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", (String) regist.get("msg"));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.grainmall.com:81/register";
                }
            }else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.grainmall.com:81/register";
            }
        }else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.grainmall.com:81/register";
        }

    }


    @PostMapping("/user/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if (login.get("code").equals(0)){
            //todo 登录成功处理 默认是作用在当前域（要解决不能再父域获取的问题）
            //todo 要使用json序列化的方式，去替换掉jdk默认的序列化 方式
            session.setAttribute(AuthServerConstant.LOGIN_USER, login.getData(new TypeReference<MemberRespVo>(){}));
            return "redirect:http://grainmall.com:81";
        }else {
            HashMap<String, Object> errors = new HashMap<>();
            errors.put("msg", login.get("msg"));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.grainmall.com:81/login";
        }
    }

    @GetMapping("/login")
    public String login(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (null != attribute){
            return "redirect:http://giranmall.com:81";
        }else {
            return "login";
        }
    }
}
